I'm so lost. I know how to use caller to get the caller method, but what do you use the get the caller class?
For example:
class Testing
def return_caller_class
return caller_class
end
end
class Parent
attr_accessor :test_me
def initialize
self.test_me = Testing.new
end
end
class Child < Parent
end
class GrandChild < Child
end
test_Parent = Parent.new
test_Child = Child.new
test_GrandChild = GrandChild.new
puts test_Parent.test_me.return_caller_class => Parent
puts test_Child.test_me.return_caller_class => Child
puts test_GrandChild.test_me.return_caller_class => GrandChild
Thank you!!!
Edit:
I've tried to do the following
class Testing
def return_caller_class
return caller[0][/`.*'/][1..-2]
end
end
And the output is:
{"
"=>Parent}
{"
"=>Child}
{"
"=>GrandChild}
To explain better about my question.
I would the output to display this instead
Parent
Child
GrandChild
I'm a bit out of my depth with this question, but I think you have made a few mistakes unrelated to the problem of getting the caller's class name. If I can help you with those things, at least you might be a step closer (if a solution is even possible)!
Firstly, it seems to me that you're calling return_caller_class from the main program object, not from one of those three objects you created. You have an object of class Testing inside an object of class Parent, but the method call is outside of both.
Secondly, the only reason you seem to be getting anything close to what you want (when you get output like "=>Parent} has nothing to do with the return_caller_class method. It seems as though you inadvertently created little hashes in the last three lines of your program (when you added => Parent, etc), which are being output with puts. (Confirmed here: Has #puts created a new hash?) If these are meant to be comments, they need a # before them.
PS. I found a link to this gem on another thread: https://github.com/asher-/sender. Might be worth checking out.
class Testing
def return_caller_class
self.class.name
end
end
class ChildOne < Testing
end
class ChildTwo < Testing
end
result:
------------------------------------------------
>ChildOne.new.return_caller_class
=> "ChildOne"
>ChildTwo.new.return_caller_class
=> "ChildTwo"
>Testing.new.return_caller_class
=> "Testing"
Related
I found the below working solutions (link 1, link 2) which call the grandparent method but without any parameters. Does anyone know how to call the grandparent method with parameters?
class GrandParent
def fun(word)
puts word
end
end
class Parent < GrandParent
def fun(word)
puts word + 'end'
end
end
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call
end
end
You can pass parameters directly to call like this:
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call(param1, param2)
end
end
call accepts parameters
GrandParent.instance_method(:fun).bind(self).call word
I don't know your use case, but this is a Really Bad Idea™. It creates unnecessary dependencies directly between Child and GrandParent such that all kinds of normally reasonable refactoring would result in a crash e.g. moving fun to only be implemented in Parent, changing Parent to subclass a different but similar parent, etc.
Sorry that I haven't made the title very clear but I honestly can't work out how to phrase my question any better; if some one can think of a better title, then please by all means change it.
Take a look at the following example:
module Foo
def method(value)
Bar.instance_exec(self.method(value))
end
class Bar
def self.method(value)
print value
end
end
end
Is that the only way to make is so Bar's method is available within the namespace of Foo without the need to call Bar or is there a more elegant way to do this? Perhaps method_missing might work but again, a bit cumbersome.
EDIT:
Further example
Module Foo
class SomeClassController < ApplicationController
def index
method(#user.id) #instead of Bar.method(#user.id)
end
end
I'm building an engine but I don't want to have to refer to Engine every time I want to use a method from it that should be available everywhere within that Main Name Space (Foo in this instance) AS there more like utility methods BUT they need to be done within the scope of Engine.
EDIT:
Turns out I wasn't using the code correctly
module Foo
def method(value)
return Bar.instance_exec(value) { |v| return self.method(value)}
end
class Bar
def self.method(value)
return (value + 59)
end
end
end
will the method inside of the block of instance_exec return outside of it so that def method within module Foo will return the correct value.
EDIT: I realise it is kind of vague but trust me when I say that instance_exec is exactly what I was searching for, that and instance_exec does in deed return outside of it's execution block.
The answer to my problem is as follows using a rails engine as the example to add a more understandable context
engine.rb:
module Foo
class Engine
class SomeClass
def method(value)
return (value + 59)
end
end
end
end
otherActions.rb
module Foo
def method(value)
return Engine.instance_exec(value){ |v| return self::SomeClass.method(v) }
end
end
Engine_Controller.rb
Module Foo
class EngineController < ApplicationController.rb
def index
#user.some_field = method(params[:user_input])
end
end
end
I think that should work well, I know everything Up to the usage of method within def index at least, that I'm not sure about but the main point of the question has been answered within otherActions.rb
I want to create an instance variable when a certain method is called and also set it to a default value. The instance should then only be able to get the variable but not set it. Here's a piece of code to showcase my problem:
class Foo
def self.bar(var)
attr_reader name.to_sym
instance_variable_set("##{var.to_s}",[var.to_s])
end
end
class Bar < Foo
bar :foo
end
puts Bar.new.foo
When I run this code I expect to get ["foo"] but instead I get nil. It seems to be a problem of scope but after fiddling around with the code for some time I just don't seem to get it right.
Edit:
I just found an exceptionally good article (read till the end) which addresses this problem very concisely. Click Me
This is I think the sort of pattern you are trying to create:
class Foo
def self.all_properties
#all_properties ||= []
end
def self.property( pr_name )
attr_reader pr_name.to_sym
instance_variable_set( "#default_#{pr_name.to_s}", [pr_name.to_s] )
all_properties << pr_name.to_sym
end
def set_default_properties
self.class.all_properties.each do | pr_name |
default = self.class.instance_variable_get( "#default_#{pr_name.to_s}" )
instance_variable_set( "##{pr_name}", default.clone )
end
end
def initialize
set_default_properties
end
end
class Bar < Foo
property :foo
end
p Bar.new.foo
It is more complex than you might initially assume. You have to put the list of managed properties, and their default values somewhere. I have done this above with the class instance variables #all_properties and #default_foo. You can get them forwarded into each instance with a little more meta-programming than you have in the question - basically a copy from defaults stashed in the class when it was defined has to be made during instantiation. Why? Because the class definition is not re-run during instantiation, it happens just once beforehand (unless you start modifying the class on-the-fly in the constructor - but that would be unusual!)
Note that the clone in the code above is not quite enough to prevent instances interfering with each other. I haven't implemented a deep clone (left as exercise to anyone reading the code), but the following variation of that line will work for the code as it stands, because the structure of default data is always the same:
instance_variable_set( "##{pr_name}", [ default[0].clone ] )
Some code
class Parent
def print
p "Hi I'm the parent"
end
end
class Child < Parent
def initialize(num)
#num = num
end
def print
child_print
end
def child_print
if #num == 1
#call parent.print
else
p "I'm the child"
end
end
end
c1 = Child.new(1)
c2 = Child.new(2)
c1.print
c2.print
Child is an instance of Parent. Print is the method exposed in the interface, and both classes define them. Child decides to do other things in a (possibly really complex) method, but will invoke its parent's method under some condition.
I could just write
def print
if #num == 1
super
else
p "I'm the child"
end
end
And that works, but what if it's not just a simple one-liner comparison but instead is doing lots of complicated things that deserve to be separated into another method? It may have to do some calculations before deciding that the parent's method should be called.
Or perhaps there is a different, better way to design it.
Parent.instance_method(:print).bind(self).call
This is already pretty readable, but here's an explanation.
Get the #print method of the Parent class
Bind it to your current object
Call it
PS: You can even give arguments to #call and they will be relayed to the called method.
PPS: That said, such code almost always hints at an issue in your class design. You should try to avoid it whenever possible.
I'm trying to learn ruby by building a basic Campfire bot to screw around with at work. I've gotten pretty far (it works!) and learned a lot (it works!), but now I'm trying to make it a bit more complex by separating the actions to be performed out into their own classes, so that they can be easier to write / fix when broken. If you're interested in seeing all the (probably crappy) code, it's all up on GitHub. But for the sake of this question, I'll narrow the scope a bit.
Ideally, I would like to be able to create plugins easily, name them the same as the class name, and drop them into an "actions" directory in the root of the project, where they will be instantiated at runtime. I want the plugins themselves to be as simple as possible to write, so I want them all to inherit some basic methods and properties from an action class.
Here is action.rb as it currently exists:
module CampfireBot
class Action
#handlers = {}
def initialize(room)
#room = room
end
class << self
attr_reader :handlers
attr_reader :room
def hear(pattern, &action)
Action.handlers[pattern] = action
end
end
end
end
Where #room is the room object, and #handlers is a hash of patterns and blocks. I kind of don't understand why I have to do that class << self call, but that's the only way I could get the child plugin classes to see that hear method.
I then attempt to create a simple plugin like so (named Foo.rb):
class Foo < CampfireBot::Action
hear /foo/i do
#room.speak "bar"
end
end
I then have my plugins instantiated inside bot.rb like so:
def load_handlers(room)
actions = Dir.entries("#{BOT_ROOT}/actions").delete_if {|action| /^\./.match(action)}
action_classes = []
# load the source
actions.each do |action|
load "#{BOT_ROOT}/actions/#{action}"
action_classes.push(action.chomp(".rb"))
end
# and instantiate
action_classes.each do |action_class|
Kernel.const_get(action_class).new(room)
end
#handlers = Action.handlers
end
The blocks are then called inside room.rb when the pattern is matched by the following:
handlers.each do |pattern, action|
if pattern.match(msg)
action.call($~)
end
end
If I do puts #room inside the initialization of Action, I see the room object printed out in the console. And if I do puts "foo" inside Foo.rb's hear method, I see foo printed out on the console (so, the pattern match is working). But, I can't read that #room object from the parent class (it comes out as a nil object). So obviously I'm missing something about how this is supposed to be working.
Furthermore, if I do something to make the plugin a bit cleaner (for larger functions) and rewrite it like so:
class Foo < CampfireBot::Action
hear /foo/i do
say_bar
end
def say_bar
#room.speak "bar"
end
end
I get NoMethodError: undefined method 'say_bar' for Foo:Class.
The definition of hear can be pulled out of the class << self block and changed to:
def self.hear(pattern, &action)
Action.handlers[pattern] = action
end
to yield the exact same result. That also immediately explains the problem. hear Is a class method. say_bar is an instance method. You can't call an instance method from a class method, because there simply isn't an instance of the class available.
To understand the class << self bit, you'll have to do your own reading and experiments: I won't try to improve on what has already been said. I'll only say that within the class << self .. end block, self refers to the eigenclass or metaclass of the CampfireBot::Action class. This is the instance of the Class class that holds the definition of the CampfireBot::Action class.